<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    -->
    <script src="/static/js/jquery.min.js"></script>
</head>
<body>
<label for="name">接收者:</label><input type="text" id="who" placeholder="要给谁发送邮件">
<button id="createTask">发送邮件</button>
<div>
    <span>任务状态：</span>
    <span id="taskStatus"></span>
</div>
<div>
    <span>任务结果：</span>
    <span id="taskResult"></span>
</div>

<script>
    let timer = null
    let index = 0

    // 获取任务结果
    function getTaskResult(taskId) {
        $.ajax("/getTaskStatus/", {
            type: 'POST',
            data: {task_id: taskId},
            dataType: 'json',
            success: function (res) {
                $("#taskStatus").text(res.msg)
                console.log(res);
                if (res.code === 0) {
                    $("#taskResult").text(res.data)
                    clearInterval(timer)
                }
            }
        })
        console.log(taskId);

    }

    // 定时轮询获取当前任务的状态
    function setTimer(taskId) {
        timer = setInterval(getTaskResult, 1000, taskId)
    }

    // 点击按钮执行任务
    $("#createTask").click(function (e) {
        // 点击发送按钮清空文本框
        $("#taskStatus").text("")
        $("#taskResult").text("")
        let who = $("#who").val()  // 邮件接受者
        // 向后端发送创建任务
        $.ajax("/createTask/", {
            type: "POST",
            dataType: 'json',
            data: {who: who},
            success: function (res) {
                if (res.code === 0) {
                    $("#taskStatus").text("任务发送")
                    setTimer(res.data.task_id)
                } else {
                    console.log("发起任务失败")
                }
            }
        })

    })


</script>
</body>
</html>